/**
 * vim: tabstop=4
 * 
 * @license		http://www.gnu.org/licenses/gpl.html GPL Version 3
 * @author		Ian Moore <imooreyahoo@gmail.com>
 * @copyright	Copyright (c) 2011 Ian Moore
 * @version		$Id: minidlna.js 73 2011-12-10 02:17:04Z imooreyahoo@gmail.com $
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this file. If not, see <http://www.gnu.org/licenses/>.
 */
// require("js/omv/NavigationPanel.js")
// require("js/omv/data/DataProxy.js")
// require("js/omv/FormPanelExt.js")
// require("js/omv/form/SharedFolderComboBox.js")
// require("js/omv/form/plugins/FieldInfo.js")
// require("js/omv/module/admin/Logs.js")
// require("js/omv/util/Format.js")
// require("js/omv/CfgObjectDialog.js")

Ext.ns("OMV.Module.Services");

// Register the menu.
OMV.NavigationPanelMgr.registerMenu("services", "minidlna", {
	text: "DLNA",
	icon: "images/minidlna.png"
});

/**
 * @class OMV.Module.Services.MiniDLNA
 * @derived OMV.FormPanelExt
 * @param config 
 */
OMV.Module.Services.MiniDLNA = function(config) {
	var initialConfig = {
		rpcService: "MiniDLNA",
		layout: "vbox",
		layoutConfig: {
			align: "stretch"
		}
	};
	Ext.apply(initialConfig, config);
	OMV.Module.Services.MiniDLNA.superclass.constructor.call(this, initialConfig);
};
Ext.extend(OMV.Module.Services.MiniDLNA, OMV.FormPanelExt, {

	initComponent : function() {

		OMV.Module.Services.MiniDLNA.superclass.initComponent.apply(this, arguments);

		// Fill media shares onload
		this.on("load", function(fpanel, data) {

			var mstore = Ext.getCmp('minidlna-shares-grid').getStore();
			mstore.removeAll();

			Ext.each(data.folders, function(f) {
                mstore.add([
                    new Ext.data.Record(f)
                ]);
			});

			// Always uncheck force rescan
			if(this.findFormField("rescan").checked) {

				this.findFormField("rescan").setValue(false);

				if(this.findFormField("enable").checked) {
                	msg = "miniDNLA will now begin to (re)scan your media folders. This may take "+
		                "several minutes. You can view its progress in the System Logs section of "+
		                "OpenMediaVault by selecting DLNA.";

        	    	// Display scan
            		OMV.MessageBox.info("Media Folders", msg);

				}
			}
		});
	},

    /* Overridden to refresh loaded data instead of original form fields */
    reset : function(){
        this.doLoad();
    },

	/* Overridden to populate folders */
	doSubmit: function() {

		var svalues = this.getValues();
		svalues.folders = new Array();

		Ext.each(Ext.getCmp('minidlna-shares-grid').getStore().getRange(),function(r) {
			svalues.folders.push({
				sfref: r.get('sfref'),
				mtype: r.get('mtype')
			});
		});

		var doSave = function(win) {
			if(typeof win != 'object') win = this;
        	OMV.MessageBox.wait(null, "Saving ...");
	        OMV.Ajax.request(win.cbSubmitHdl, win, "MiniDLNA", "set", [ svalues ]);
		};

		if(svalues.enable && !svalues.rescan) {

        	// Display waiting dialog
			OMV.MessageBox.info("DLNA Media Folders","If you have made changes to your "+
				"Media Folders, miniDNLA will begin to (re)scan them for media. This may take "+
				"several minutes. You can view its progress in the System Logs section of "+
				"OpenMediaVault by selecting DLNA.", doSave, this);

		} else {

			doSave(this);
		}

	},

	getFormItems : function() {
		return [{
			xtype: "fieldset",
			title: "General settings",
			defaults: {
				labelSeparator: ""
			},
			items: [{
				xtype: "checkbox",
				name: "enable",
				fieldLabel: "Enable",
				checked: false,
				inputValue: 1
			},{
				xtype: "textfield",
				name: "name",
				width: 300,
				value: "MiniDLNA on OpenMediaVault",
				fieldLabel: "Name",
                plugins: [ OMV.form.plugins.FieldInfo ],
                infoText: "The name that is displayed to DLNA clients."
			},{
				xtype: "numberfield",
				name: "port",
				fieldLabel: "Port",
				vtype: "port",
				minValue: 0,
				maxValue: 65535,
				allowDecimals: false,
				allowNegative: false,
				allowBlank: false,
				value: 8200,
				plugins: [ OMV.form.plugins.FieldInfo ],
				infoText: "Port to listen on."
			},{
                xtype: "checkbox",
                name: "strict",
                fieldLabel: "Strict DLNA",
				boxLabel: "Strictly adhere to DLNA standards",
                checked: false,
                inputValue: 1,
                plugins: [ OMV.form.plugins.FieldInfo ],
                infoText: "This will allow server-side downscaling of very large JPEG images"
			},{
                xtype: "checkbox",
                name: "tivo",
                fieldLabel: "TiVo support",
                checked: false,
                inputValue: 1
			},{
				xtype: "checkbox",
				name: "rescan",
				fieldLabel: "Media Rescan",
				checked: false,
				inputValue: 1,
				boxLabel: "Force a complete rescan of all media folders"
			},{
				xtype: "label",
				html: "A complete rescan should not normally be needed. When files / folders are updated (added/deleted/modified), "+
					"miniDLNA will automatically rescan updated items.<br /><br />"
			}]
		},{
			xtype: 'fieldset',
			title: 'Donate',
			items: [{
				html: 'I develop plugins for OpenMediaVault in my spare time, free of charge. If you find this plugin useful, I ask that you please donate.'
			},{
				html: "<div style='margin:10px'><a href='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=PPYY2F9ST2BAY' target=_blank><img width='147' height='47' src='images/donate-btn.gif' /></a></div>"
			}]
		},{
			xtype: "panel",
			frame: true,
			title: "Media Folders (Media folders and files must be readable by the 'minidlna' user)",
			layout: 'fit',
			boxMinHieght: 200,
			flex: 1,
			items: [{
				xtype: "grid",
				id: 'minidlna-shares-grid',
            	tbar: [{
                	id: this.getId() + "-add",
	                xtype: "button",
	                text: "Add",
    	            icon: "images/add.png",
					handler: function() {
        				var wnd = new OMV.Module.Services.MiniDLNAFolderPropertyDialog({
				            uuid: OMV.UUID_UNDEFINED
        				});
        				wnd.show();
					}
				},{
                    id: this.getId() + "-edit",
                    xtype: "button",
                    text: "Edit",
                    icon: "images/edit.png",
					handler: function(b) {
        				var record = b.ownerCt.ownerCt.getSelectionModel().getSelected();
                        var wnd = new OMV.Module.Services.MiniDLNAFolderPropertyDialog({
                            uuid: 'dummy',
							sfref: record.get('sfref'),
							mtype: record.get('mtype')
                        });
                        wnd.show();
					}
				},{
                    id: this.getId() + "-remove",
                    xtype: "button",
                    text: "Remove",
                    icon: "images/delete.png",
					handler: function(b) {
						b.ownerCt.ownerCt.getStore().remove(
							b.ownerCt.ownerCt.getSelectionModel().getSelected()
						);
					}
	            }],
	            viewConfig: { forceFit: true },
	            sm: new Ext.grid.RowSelectionModel({
	                singleSelect:true
	            }),
            	store: new Ext.data.SimpleStore({
                	fields: [
						{ name: "sfref" },
						{ name: "name" },
						{ name: "mtype" }
					],
               		data: [ ]
            	}),
				columns: [{
					header: "Share",
					dataIndex: "name"
				},{
					header: "Content Type(s)",
					dataIndex: "mtype",
					renderer: function(val) {

						switch(val) {
							case 'A': return 'Audio';
							case 'V': return 'Video';
							case 'P': return 'Images';
						}
						return 'All';
					}
				}]

			}]
		}];
	}

});
OMV.NavigationPanelMgr.registerPanel("services", "minidlna", {
	cls: OMV.Module.Services.MiniDLNA
});

/**
 * @class OMV.Module.Diagnostics.LogPlugin.MiniDLNA
 * @derived OMV.Module.Diagnostics.LogPlugin
 * Class that implements the 'MiniDLNA' log file diagnostics plugin
 * @param config
 */
OMV.Module.Diagnostics.LogPlugin.MiniDLNA = function(config) {
    var initialConfig = {
        title: "DLNA",
        stateId: "c9d06952-00da-11e1-aa29-minidlna",
        columns: [{
            header: "Date & Time",
            sortable: true,
            dataIndex: "date",
            id: "date",
            width: 20,
			renderer: OMV.util.Format.localeTimeRenderer()
		},{
			header: "Component",
			sortable: true,
			dataIndex: "component",
			width: 20
        },{
            header: "Event",
            sortable: true,
            dataIndex: "event",
            id: "event"
        }],
        rpcArgs: "minidlna",
        rpcFields: [
            { name: "date" },
            { name: "component" },
            { name: "event" }
        ]
    };
    Ext.apply(initialConfig, config);
    OMV.Module.Diagnostics.LogPlugin.MiniDLNA.superclass.constructor.call(
      this, initialConfig);
};
Ext.extend(OMV.Module.Diagnostics.LogPlugin.MiniDLNA,
  OMV.Module.Diagnostics.LogPlugin, {
});
OMV.preg("log", "minidlna", OMV.Module.Diagnostics.LogPlugin.MiniDLNA);


/**
 * Media folder edit dialog
 */
OMV.Module.Services.MiniDLNAFolderPropertyDialog = function(config) {
    var initialConfig = {
        title: ((config.uuid == OMV.UUID_UNDEFINED) ? "Add" : "Edit") +
          " media folder",
        autoHeight: true
    };
    Ext.apply(initialConfig, config);
    OMV.Module.Services.MiniDLNAFolderPropertyDialog.superclass.constructor.call(
      this, initialConfig);
};
Ext.extend(OMV.Module.Services.MiniDLNAFolderPropertyDialog, OMV.CfgObjectDialog, {

	// Override doLoad since we aren't actually
	// making an RPC call
	doLoad: function() {
		this.setValues({
			mtype: this.mtype,
			sharedfolderref: this.sfref
		});
		this.fireEvent("load", this);
	},

	// Override doSubmit since we aren't
	// actually making an RPC call
	doSubmit: function() {

		var vals = this.getValues();

		var sfstore = Ext.getCmp('minidlna-sharedfolder-combo').getStore();

		f = { name : sfstore.getById(vals.sharedfolderref).get('name'),
			mtype: vals.mtype,
			sfref: vals.sharedfolderref
		};

		// Add or replace
		if(this.uuid == OMV.UUID_UNDEFINED) {
    		Ext.getCmp('minidlna-shares-grid').getStore().add([
            	new Ext.data.Record(f)
	        ]);
		} else {
			var record = Ext.getCmp('minidlna-shares-grid').getSelectionModel().getSelected();
			for(var k in f) {
				if ( typeof k == 'string') record.set(k, f[k]);
			}
		}
		this.close();
	},

    initComponent : function() {
        OMV.Module.Services.MiniDLNAFolderPropertyDialog.superclass.initComponent.
          apply(this, arguments);
        this.on("load", this._updateFormFields, this);
    },

    getFormConfig : function() {
        return {
            autoHeight: true
        };
    },

    getFormItems : function() {
        return [{
            xtype: "sharedfoldercombo",
            name: "sharedfolderref",
            hiddenName: "sharedfolderref",
            fieldLabel: "Shared folder",
			id: 'minidlna-sharedfolder-combo',
            plugins: [ OMV.form.plugins.FieldInfo ],
            infoText: "Shared folder containing media files."
        },{
            xtype: "combo",
            name: "mtype",
            fieldLabel: "Scan media types",
            mode: "local",
            store: new Ext.data.SimpleStore({
                fields: [ "value","text" ],
                data: [
                       [ "","All" ],
                       [ "A","Audio" ],
                       [ "V","Video" ],
                       [ "P","Images" ],
                       ]
            }),
			value: "",
            displayField: "text",
            valueField: "value",
            allowBlank: false,
            editable: false,
            triggerAction: "all"
        },{
            xtype: "hidden",
            name: "mntentref",
            value: OMV.UUID_UNDEFINED
        }];
    },

    /**
     * Private function to update the states of various form fields.
     */
    _updateFormFields : function() {
        var field = this.findFormField("sharedfolderref");
        if ((this.uuid !== OMV.UUID_UNDEFINED) && Ext.isDefined(field)) {
            field.setReadOnly(true);
        }
    }
});

